package com.ithema.reggie.controller;

import cn.hutool.core.util.RandomUtil;
import com.ithema.reggie.common.R;
import com.ithema.reggie.entity.User;
import com.ithema.reggie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    UserService userService;

    @PostMapping("sendMsg")
    public R sendMsg(@RequestBody User user, HttpSession session){
        //获取手机号
        String phone = user.getPhone();

        //2.生成随机的验证码，生成为4位的纯数字的验证码
        String code = RandomUtil.randomNumbers(4);

        //3.模拟法验证码
        System.out.println(code);

        //设置验证码为1234
        code = "1234";

        //4.为了后期和用户输入验证码进行比较，要将验证码放入session中
        session.setAttribute(phone,code);
        return R.success(null);

        /*
        //3.调用工具类发送短信(只是写代码,不演示)
        try {
            SendSmsResponse response = SmsUtil.sendSms(phone, code);
            //若成功了获取code就是ok
            if (StrUtil.equalsIgnoreCase(response.getCode(),"ok")) {
                //4.为了后期和用户输入验证码进行比较,要将验证码放入session中
                session.setAttribute(phone,code);
                return R.success(null);
            }else {
                throw new BusinessException("发送失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("发送失败:"+e.getMessage());
        }
        */
    }

    @PostMapping("login")
    public R login(@RequestBody Map<String,String> map,HttpSession session){
        //1.获取用户输入的手机号和验证码
        String requestCode = map.get("code");
        String phone = map.get("phone");

        //2.获取session中验证码
        String sessionCode = (String) session.getAttribute(phone);

        //3.调用service完成登陆注册
        R<User> r = userService.login(phone,requestCode,sessionCode);

        //4.若用户登陆成功,将用户id存入session中,把验证码从session中删除
        if (r.getCode()==1) {
            session.setAttribute("user",r.getData().getId());
            session.removeAttribute(phone);
        }

        return r;
    }


}
